/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package ace.game.particle;

import ace.game.entity.Entity;
import ace.geometry.Vector2D;
import ace.geometry.Vertex2D;
import ace.system.StateManager;
import javax.microedition.lcdui.Graphics;

/**
 *
 * @author Hallucinogen
 */
public class Particle extends Entity {

	public Particle(ParticleEmitter emitter) {
		mEmitter = emitter;
		position = new Vertex2D();
	}

	public Particle(ParticleEmitter emitter, Vertex2D inPos, Vector2D direction, long aliveTime, int color) {
		this(emitter);
		initParticle(inPos, direction, aliveTime, color);
	}

	public void initParticle(Vertex2D inPos, Vector2D direction, long aliveTime, int color) {
		if (inPos != null) {
			position	= inPos;
		} else {
			position.x = mEmitter.position.x;
			position.y = mEmitter.position.y;
		}
		mDirection	= direction;
        mAliveTime  = aliveTime;
		mColor		= color;

		mAlive          = true;
		mElapsedTime	= 0;
	}

	public void update(long time) {
		mElapsedTime += time;
		if (mElapsedTime > mAliveTime) {
			mAlive = false;
			return;
		}
        final float aliveFactor = (float)(mAliveTime - mElapsedTime) / (float)(mAliveTime);
        // limit the decceleration to 0.7
        final float deccelerationFactor = 0.7f + 0.3f * aliveFactor;
        position.add(mDirection);
        mDirection.x *= deccelerationFactor;
        mDirection.y *= deccelerationFactor;
		mDirection.add(mEmitter.getRandomizedForce());
	}

	public boolean isAlive() { return mAlive; }

	public void draw(Graphics g, int startX, int startY, int endX, int endY) {
		if (!isAlive()) return;
		int Left	= (int)(position.x - startX );
		int Top		= (int)(position.y - startY );

		//Ensure in drawing area
		if (Left < 0)										return;
		else if(Left > endX)                                return;
		else if (Top < 0)									return;
		else if (Top > StateManager.instance().getHeight())	return;

		g.setColor(mColor);
		g.drawLine(Left, Top, (int)(Left + mDirection.x), (int)(Top + mDirection.y));
		g.setColor(0x000000);
	}

	private ParticleEmitter mEmitter;
	private Vector2D mDirection;
	private long mElapsedTime, mAliveTime;
	private boolean mAlive;
	private int mColor;
}
